package com;

import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class MyHandlerAdapter implements HandlerAdapter {

    /**
     * supports：支持，我能干什么
     * <p>
     * 下面的逻辑是类上有MyController注解修饰以及有process方法
     *
     * @param handler
     * @return
     */
    @Override
    public boolean supports(Object handler) {

        Class<?> aClass = handler.getClass();
        boolean haveMyController = aClass.isAnnotationPresent(MyController.class);
        Method method = null;
        try {
            method = aClass.getDeclaredMethod("process", HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return haveMyController && method != null;


    }

    @Override
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Class<?> aClass = handler.getClass();
        Method method = aClass.getDeclaredMethod("process", HttpServletRequest.class, HttpServletResponse.class);
        ModelAndView mav = (ModelAndView) method.invoke(handler, request, response);
        return mav;
    }

    @Override
    public long getLastModified(HttpServletRequest request, Object handler) {
        return 0;
    }
}
